<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<title>WebSocketClient</title>
	<script src='https://code.jquery.com/jquery-1.8.0.min.js' type='text/javascript'></script>
	<script type="text/javascript" th:inline="javascript">
		window["profileActive"] = [[${profileActive}]];
		window["serverPort"] = [[${serverPort}]];
	</script>
	<script src="js/test-config.js" type="application/javascript"></script>
	<script src="js/easyj-websocket-client.js" type="application/javascript"></script>

	<style>
		#toolbar {
			position: fixed;
			width: 100%;
			height: 100px;
			top: 0;
			left: 0;
			padding: 10px;
		}

		#toolbar select, #toolbar input {
			margin-right: 20px;
		}

		#message {
			margin-top: 100px;
		}
	</style>
</head>
<body>
<div id="main">
	<div id="toolbar">
		<label for="type">type:</label>
		<select id="type">
			<option value="subscribe">订阅消息</option>
			<option value="unsubscribe">取消订阅消息</option>
		</select>
		<label for="channel">channel: </label><input id="channel" value="aaa" style="width: 300px"/>
		<label for="id">id: </label><input id="id" value="1" style="width: 100px"/>
		<input type="button" value="提交" onclick="submit()"/>
	</div>
	<div id="message"></div>
</div>
</body>
<script type="text/javascript">
	// 创建连接对象
	const wsc = new WebSocketClient({
		url: config.wsrUrl || config.wsUrl,
		spareWsUrl: [config.wsUrl]
	});
	// 设置各事件回调方法
	wsc.onopen = function (open) {
		console.info("自定义回调方法：onopen");
		setMessageInnerHTML("连接成功");
	};
	wsc.onmessage = function (event) {
		console.info("自定义回调方法：onmessage");
		setMessageInnerHTML("接收到了一个消息：" + '<span style="color:darkgreen">' + event.data + '</span>');
	};
	wsc.onclose = function (close) {
		console.info("自定义回调方法：onclose");
		setMessageInnerHTML('<span style="color:red">连接关闭,如需登录请刷新页面。');
	};
	wsc.onerror = function (error) {
		console.info("自定义回调方法：onerror");
		setMessageInnerHTML('<span style="color:red">连接发生错误</span>');
	};


	/***** 其他方法 *****/

	// 将消息显示在网页上，如果不需要显示在网页上，则不调用该方法
	function setMessageInnerHTML(innerHTML) {
		document.getElementById('message').innerHTML += innerHTML + '<br/>';
	}

	// 向服务器发送订阅消息
	function sendToServer(type, channel, id) {
		if (!channel) return;
		if (!type) type = "subscribe";

		if (type === "subscribe") {
			wsc.subscribe(channel, id, function (json, event) {
				setMessageInnerHTML('<span style="color:darkgreen">接收到通过表单订阅的：channel=' + channel + ', id=' + id + ", message=" + json.message + ", event.data=" + event.data + '</span>');
			});
		} else if (type === "unsubscribe") {
			wsc.unsubscribe(channel, id);
		} else {
			alert("暂不支持测试type=" + type + "的消息");
		}
	}

	function submit() {
		let type = document.getElementById("type").value;
		let channel = document.getElementById("channel").value;
		let id = document.getElementById("id").value;

		sendToServer(type, channel, id);
	}
</script>
</html>